JavaScript syntax
part 14/43 Β· 161.3 KB total
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
primitive. However, the typeof operator does not return boolean for the
object wrapper, it returns object. Because all objects evaluate as true,
a method such as .valueOf(), or .toString(), must be used to retrieve
the wrapped value. For explicit coercion to the Boolean type, Mozilla
recommends that the Boolean() function (without new) be used in
preference to the Boolean object.
const b = new Boolean(false); // Object false {}
const t = Boolean(b); // Boolean true
const f = Boolean(b.valueOf()); // Boolean false
let n = new Boolean(b); // Not recommended
n = new Boolean(b.valueOf()); // Preferred
if (0 || -0 || "" || null || undefined || b.valueOf() || !new Boolean()
|| !t) {
console.log("Never this");
} else if ([] && {} && b && typeof b === "object" && b.toString() ===
"false") {
console.log("Always this");
}
Symbol
Symbols are a feature introduced in ES6. Each symbol is guaranteed to be
a unique value, and they can be used for encapsulation.cite-ref-15[15]
Example:
let x = Symbol(1);
const y = Symbol(1);
x === y; // => false
const symbolObject = {};
const normalObject = {};
// since x and y are unique,
// they can be used as unique keys in an object
symbolObject[x] = 1;
symbolObject[y] = 2;
symbolObject[x]; // => 1
symbolObject[y]; // => 2
// as compared to normal numeric keys
normalObject[1] = 1;
normalObject[1] = 2; // overrides the value of 1
normalObject[1]; // => 2
// changing the value of x does not change the key stored in the object
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ